/**
 * 接收微信平台定时回调信息
 * @authors 杨兴洲（of2502）
 * @date    2017/2/22 15:58
 * @version 1.0
 */

import {Router} from "express";
import {decrypt} from "../util/cryptor-util";
import {getReqRawBody} from "../util/request-util";
import XMLUtil from "../util/xml-util";
import logger from "../util/logger";
import CONFIG from "../config";
import UserService from "../service/user-service";
import LogService from "../service/log-service";
import SiteService from "../service/site-service";
import ReplyService from "../service/reply-service";
import MassSendService from "../service/massSend-service";
import MediaService from "../service/media-service";
import MCService from "../service/mc-service";

const router = Router();

/**
 * 接收微信平台定时回调信息
 * 1.存储verifyTicket 2.返回success
 */
router.post('/', (req, res, next) => {
    (async () => {
        try {
            const data = await getWeixinPushData(req);
            await handlePushData(data);
            res.status(200).end("success");
        } catch (error) {
            next(error);
        }
    })();
});


export default router;

/**
 * 获取微信推送信息
 * 1.获取 2.解密 3.XML => JSON
 * @param req
 * @returns {Promise<any>}
 * InfoType
 *  - 接收 component_verify_ticket /infoType为空
 *  - 接收授权成功通知/authorized
 *  - 接收取消授权通知/unauthorized: 移除授权信息
 *  - 接收更新授权通知/updateauthorized:
 */
async function getWeixinPushData(req: any): Promise<any> {
    let rawBody = await getReqRawBody(req);
    let result = await XMLUtil.parse2Json(rawBody);
    let Encrypt = decrypt(result['Encrypt']);
    let msgContent = await XMLUtil.parse2Json(Encrypt.message);
    logger.debug(msgContent);
    return msgContent;
}

/**
 * 处理微信推送信息
 * @param data
 */
async function handlePushData(data: WeixinPushData): Promise<void> {
    logger.info(`-----------------接收${data.InfoType}事件推送----------------------`);

    if (data.InfoType === 'component_verify_ticket') { // 接受ticket
        if (CONFIG.appID !== data["AppId"]) { // 可能存在其他第三方平台恶意授权过来
            logger.info(data["AppId"], "其他第三方平台推送Ticket");
            return;
        }

        const verifyTicket = data["ComponentVerifyTicket"];
        await SiteService.updateInfo({verifyTicket});
        logger.info(verifyTicket);

    } else if (data.InfoType === 'unauthorized') { // 取消授权
        const appID = data.AuthorizerAppid;
        const {userID} = await UserService.getInfoByAppID(appID);

        // 通知MC中心解绑公众号
        await MCService.unbind(userID).catch(error => console.log(error));
        await UserService.removeInfoByAppID(appID).catch(error => console.log(error));
        // 移除相关规则: keyword && reply && massSend && 删除素材绑定库
        await ReplyService.deleteRules(appID).catch(error => console.log(error));
        await MassSendService.deleteUserMsg(userID).catch(error => console.log(error));
        await MediaService.deleteUserMedia(appID).catch(error => console.log(error));
        // 记录日志
        await LogService.create({appID, userID, actionType: data.InfoType});
    } else if (data.InfoType === 'authorized') { // 授权成功

    } else if (data.InfoType === 'updateauthorized') { // 更新授权

    }

    logger.info('------------------------------------------------------');
}

/*=============================interface=====================================*/
interface WeixinPushData {
    AppId: string,
    CreateTime: string,
    InfoType: string,
    ComponentVerifyTicket?: string, // 获取ticket
    AuthorizerAppid?: string, // 获取/更新/取消授权
    AuthorizationCode?: string, // 获取/更新授权
    AuthorizationCodeExpiredTime?: string, //获取/更新授权
}
